import Vue from 'vue'
import VueRouter from 'vue-router'
import { getItem } from '@/utils/storage.js'
import { getToken } from '@/api/user.js'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout'),
    children: [
      // 默认子路由
      {
        path: '',
        component: () => import('@/views/home')
      },
      {
        path: '/video',
        component: () => import('@/views/video')
      },
      {
        path: '/qa',
        component: () => import('@/views/qa')
      },
      {
        path: '/profile',
        component: () => import('@/views/profile')
      }
    ]
  },
  {
    path: '/user',
    component: () => import('@/views/user')
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/search',
    component: () => import('@/views/search')
  },
  {
    path: '/article/:articleId',
    name: 'article', // 练习不用加
    props: true, // 代表开启props获取参数
    component: () => import('@/views/article')
  },
  // {
  //   path: '/article',
  //   name: 'article',
  //   component: () => import('@/views/article')
  // },
  {
    path: '/test',
    component: () => import('@/views/test')
  }
]

const router = new VueRouter({
  routes
})

// 约定的过期时间
const tokenTimeOut = 1 * 60 * 1000

router.beforeEach(async (to, from, next) => {
  console.log('判断token有没有过期')
  // 获取登陆的时间戳
  const loginDate = getItem('TOKENDATE')
  // 获取进入页面的当前时间戳
  const currentDate = Date.now()
  if ((currentDate - loginDate) > tokenTimeOut && store.state.user && store.state.user.token) {
    // 刷新token
    const res = await getToken()
    store.commit('initUser', {
      ...store.state.user,
      token: res.data.data.token
    })
  }
  next()
})

export default router
